import { useSearchParams } from 'react-router-dom';
import Hook from '@/assets/AiImgs/Hook.png';
import pic1 from '@/assets/img/course-1.png';
import pic2 from '@/assets/img/course-2.png';
import Zuo from '@/assets/AiImgs/zuokuohao.png';
import You from '@/assets/AiImgs/youkuohao.png';
import qingzhu from '@/assets/AiImgs/qingzhu@3x.png';
import nuli from '@/assets/AiImgs/nuli.png';
import bucuo from '@/assets/AiImgs/bucuo.png';
import jiayou from '@/assets/AiImgs/jiayou.png';
import loadingImg from '@/assets/AiImgs/loadingReport.png';
import ReactECharts from 'echarts-for-react';
import { useEffect, useMemo, useState, useRef } from 'react';
import { getTrainReport } from '@/api/train';
import './index.less';

// 类型定义
interface DimensionScore {
  dimension_name?: string;
  full_score?: number;
  score?: number;
}

interface OverallComment {
  result?: number;
  comment?: string[];
}

interface DetailAnalysis {
  dimension_name?: string;
  score?: number;
  comment?: string;
}

interface PageData {
  overall_score?: {
    full_score?: number;
    score?: number;
    dimension_scores?: DimensionScore[];
  };
  overall_comment?: OverallComment;
  detail_analysis?: DetailAnalysis[];
}

// 统一props定义
interface TrainingReportProps {
  reportResult?: number;
  onNotify?: (data: { message: string }) => void; // 将onNotify定义为函数类型
}

type CommentType = 0 | 1 | 2 | 3;

const COMMENT_ICON_MAP: Record<CommentType, { icon: string; text: string; }> = {
  0: { icon: nuli, text: '还需努力' },
  1: { icon: qingzhu, text: '非常棒' },
  2: { icon: bucuo, text: '表现不错' },
  3: { icon: jiayou, text: '继续加油' }
};

// 合并参数接收
export default function TrainingReport({ reportResult, onNotify }: TrainingReportProps) {
  const [searchParams] = useSearchParams();
  const [chartOption, setChartOption] = useState({});
  const picid = searchParams.get('prcid');
  const [pageData, setPageData] = useState<PageData>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  
  // 使用 ref 存储定时器
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  
  // 使用 ref 跟踪轮询状态
  const isPolling = useRef(false);

  // 使用ref标记是否已通知过父组件，避免多次调用
  const hasNotified = useRef(false);

  useEffect(() => {
    if (!picid) {
      setError(true);
      setLoading(false);
      return;
    }

    setLoading(true);
    setError(false);
    
    // 标记开始轮询
    isPolling.current = true;

    // 定义获取数据的函数
    const fetchData = () => {
      getTrainReport(picid)
        .then((res: any) => {
          if (res?.code === 2000 && res?.data) {
            // 更新页面数据
            setPageData(res.data || {});
            
            // 检查是否需要继续轮询
            const shouldContinuePolling = !res.data?.detail_analysis || res.data.detail_analysis.length <= 0;
            
            if (shouldContinuePolling) {
              // 如果数据不完整，继续轮询
              timerRef.current = setTimeout(fetchData, 2000);
              return;
            }
            
            // 数据完整，处理雷达图
            const dimensionScores = res.data?.overall_score?.dimension_scores || [];
            const radaData = dimensionScores.map((m: DimensionScore = {}) => {
              return { 
                name: m.dimension_name || '未知维度', 
                max: m.full_score || 30 
              };
            });
            
            // 检查onNotify是否存在，安全调用
            if (onNotify && !hasNotified.current) {
              onNotify({ message: "1" });  // 告知父组件，拿到数据
              hasNotified.current = true; // 标记为已通知
            }
            
            const radaScoreData = dimensionScores.map((m: DimensionScore = {}) => m.score || 0);

            setChartOption({
              backgroundColor: '#fff',
              tooltip: { show: false },
              radar: {
                shape: 'circle',
                center: ['50%', '50%'],
                radius: "50%",
                indicator: radaData,
                axisName: {
                  formatter: function(name: any) {
                    const index = radaData?.findIndex((item: any) => item.name === name);
                    const value = radaScoreData[index];
                    return [`{a|${name}}`, `{b|${value}}`].join('\n\n');
                  },
                  rich: {
                    a: { fontSize: 12, color: '#000000' },
                    b: { 
                      fontSize: 16, 
                      color: '#000', 
                      fontWeight: 'bold', 
                      align: 'center', 
                      fontFamily: 'SpeedeeApp-BoldItalic' 
                    }
                  }
                },
                name: { textStyle: { padding: [3, 5], color: '#000000' } },
                axisLine: { 
                  lineStyle: { 
                    show: false, 
                    type: 'dashed', 
                    width: 1, 
                    color: 'rgba(0, 0, 0, 0.08)' 
                  } 
                },
                splitNumber: 2,
                splitArea: { show: false },
                splitLine: { show: true, type: 'dashed' }
              },
              series: [{
                type: 'radar',
                data: [{
                  value: radaScoreData,
                  areaStyle: { color: '#FFBC0D' },
                  itemStyle: { color: '#FFBC0D', width: 0 },
                  symbol: 'none'
                }],
                lineStyle: { show: false, width: 0 }
              }],
              grid: { left: '20%', right: '20%' }
            });
            
            // 数据完整，停止轮询
            isPolling.current = false;
            setLoading(false);
          } else {
            setError(true);
            setLoading(false);
          }
        })
        .catch(err => {
          console.error('获取训练报告失败:', err);
          setError(true);
          setLoading(false);
        });
    };

    // 首次调用获取数据
    fetchData();
    
    // 清理函数，取消未完成的定时器
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
      isPolling.current = false;
      hasNotified.current = false; // 重置通知状态
    };
  }, [picid, onNotify]); // 添加onNotify到依赖数组
  
  // 综合评价文本
  const overallCommentText = useMemo(() => {
    const value = (pageData?.overall_comment?.result ?? 0) as CommentType;
    const { icon, text } = COMMENT_ICON_MAP[value] || COMMENT_ICON_MAP[0];
    
    return (
      <>
        <img src={icon} className='w-[20px] inline align-sub' alt={text} />
        <span>{text}</span>
      </>
    );
  }, [pageData]);

  // 渲染加载状态
  if (loading || isPolling.current) {
    return (
      <div className='bg-white h-[73vh] overflow-hidden flex items-center justify-center flex-col'>
        <img className='w-[276px] h-[276px]' src={loadingImg} alt="加载中" />
        <div className='text-center text-[#222222] mt-4'>
          <div className='text-base' style={{ fontFamily: 'PingFangTC-Semibold' }}>
            {reportResult === 0 ? '正在评分中...' : '正在加载报告...'}
          </div>
          <div className='text-sm' style={{ fontFamily: 'PingFangSC-Light' }}>
            别急别急AI小助手正在认真算分呢
          </div>
        </div>
      </div>
    );
  }

  // 处理错误状态
  if (error || !pageData || Object.keys(pageData).length === 0) {
    return (
      <div className='bg-white h-[73vh] overflow-hidden flex items-center justify-center flex-col'>
        <div className='text-center text-[#222222]'>
          <div className='text-base mb-4' style={{ fontFamily: 'PingFangTC-Semibold' }}>
            数据加载失败
          </div>
          <div className='text-sm' style={{ fontFamily: 'PingFangSC-Light' }}>
            无法获取报告数据，请稍后再试
          </div>
          <button 
            className="mt-4 px-6 py-2 bg-yellow-500 text-white rounded-full font-medium hover:bg-yellow-600 transition"
            onClick={() => {
              setLoading(true);
              setError(false);
              // 重新获取数据
              const fetchData = () => {
                getTrainReport(picid)
                  .then((res: any) => {
                    if (res?.code === 2000 && res?.data) {
                      setPageData(res.data || {});
                      setLoading(false);
                    } else {
                      setError(true);
                      setLoading(false);
                    }
                  })
                  .catch(err => {
                    console.error('获取训练报告失败:', err);
                    setError(true);
                    setLoading(false);
                  });
              };
              fetchData();
            }}
          >
            重新加载
          </button>
        </div>
      </div>
    );
  }

  // 安全获取数据方法
  const getSafeValue = <T,>(obj: any, path: string, defaultValue: T): T => {
    return path.split('.').reduce((acc, part) => acc?.[part], obj) ?? defaultValue;
  };

  // 获取安全数据
  const fullScore = getSafeValue(pageData, 'overall_score.full_score', 0);
  const overallScore = getSafeValue(pageData, 'overall_score.score', 0);
  const overallComments = getSafeValue<string[]>(pageData, 'overall_comment.comment', []);
  const detailAnalysis = getSafeValue<DetailAnalysis[]>(pageData, 'detail_analysis', []);

  return (
    <div className="h-[75vh] overflow-y-auto overflow-x-hidden pb-6 reportPage">
      {/* 综合得分部分 */}
      <div className="items-start gap-3 pt-6 bg-white rounded-tr-2xl">
        <h2 className='text-base font-normal text-center pb-3'>
          综合得分(满分{fullScore}分)
        </h2>
        <div className="text-[#DB0007] text-4xl text-center font-bold leading-9 borderBG mb-3.5" 
             style={{ fontFamily: 'SpeedeeApp-Bold' }}>
          {overallScore}
        </div>
        {/* 雷达图部分 */}
        {pageData.overall_score?.dimension_scores?.length ? (
          <ReactECharts option={chartOption} style={{ height: 280 }} />
        ) : (
          <div className="h-[280px] flex items-center justify-center text-gray-500">
            无雷达图数据
          </div>
        )}
      </div>
      
      {/* 综合评价部分 */}
      <div className="items-start gap-3 p-6 bg-white rounded-2xl relative mt-[10px]">
        <div className='absolute -top-5 pr-12 w-full'>
          <img className='w-[6px] inline-block' src={Hook} alt="装饰" />
          <img className='w-[6px] inline-block float-right' src={Hook} alt="装饰" />
        </div>
        <h2 className='text-xl font-bold text-center pb-6 border-b border-gray-100'>
          <div className='flex justify-center items-center'>
            <img src={Zuo} className='w-3 h-7 mr-1.5' alt="左括号" /> 
            综合评价 
            <img src={You} className='w-3 h-7 ml-1.5' alt="右括号" />
          </div>
        </h2>
        <div>
          <div className='py-4 block text-base font-bold'>
            <div className='flex box-content'>
              <div>
                {overallCommentText}!
                <div className={`h-1.5 bg-[#ffbc0d7f] ml-0.5`} 
                     style={{ width: overallCommentText ? '88px' : '70px' }}></div>
              </div>
            </div>
          </div>
          <dl className="max-w-xl space-y-2 text-sm/6 text-gray-600 lg:max-w-none">
            {overallComments.map((comment, index) => (
              <div className="flex items-stretch" key={index}>
                <div className='pt-2'>
                  <svg width="6" height="6">
                    <circle cx="3" cy="3" r="2" stroke="#FFBC0D" strokeWidth="2" fill="none" />
                  </svg>
                </div>
                <div className="text-[#222222] ml-1 leading-6">{comment}</div>
              </div>
            ))}
          </dl>
        </div>
      </div>
      
      {/* 推荐课程部分 */}
      <div className="items-start gap-3 p-6 bg-white rounded-2xl relative mt-[10px]">
        <div className='absolute -top-5 pr-12 w-full'>
          <img className='w-[6px] inline-block' src={Hook} alt="装饰" />
          <img className='w-[6px] inline-block float-right' src={Hook} alt="装饰" />
        </div>
        <h2 className='text-xl font-bold text-center pb-6 border-b border-gray-100'>
          <div className='flex justify-center items-center'>
            <img src={Zuo} className='w-3 h-7 mr-1.5' alt="左括号" />
            推荐课程
            <img src={You} className='w-3 h-7 ml-1.5' alt="右括号" />
          </div>
        </h2>
        <ul role="list" className="grid gap-x-8 sm:grid-cols-2 sm:gap-y-16 xl:col-span-2">
          <li className='mt-5'>
            <div className="flex items-center gap-x-6">
              <div className='img-box'>
                <img src={pic1} className='w-[65px] cour-img' alt="安全的值班" />
              </div>
              <div style={{flex:1}}>
                <h3 className="text-base/5 font-semibold tracking-tight text-[#222222] text-sm">
                  安全的值班
                </h3>
                <div className='text-xs text-[#666666] mt-1'>
                  <span className='border px-2 py-px even:ml-1 rounded-full'>卫生消毒</span>
                  <span className='border px-2 py-px even:ml-1 rounded-full'>食品安全</span>
                </div>
                <div className='text-status'>已完成</div>
              </div>
            </div>
          </li>
          <li className='mt-5'>
            <div className="flex items-center gap-x-6">
              <div className='img-box'>
                <img src={pic2} className='w-[65px] cour-img' alt="食品安全&创造良好的顾客体验" />
              </div>
              <div>
                <h3 className="text-base/7 font-semibold tracking-tight text-[#222222] text-sm">
                  创造良好的顾客体验
                </h3>
                <div className='text-xs text-[#666666] mt-1'>
                  <span className='border px-2 py-px even:ml-1 rounded-full'>食品安全</span>
                </div>
                <div className='text-status'>未进行</div>
              </div>
            </div>
          </li>
        </ul>
      </div>
      
      {/* 明细解析部分 */}
      <div className="items-start gap-3 p-6 bg-white rounded-t-2xl relative mt-[10px]">
        <div className='absolute -top-5 pr-12 w-full'>
          <img className='w-[6px] inline-block' src={Hook} alt="装饰" />
          <img className='w-[6px] inline-block float-right' src={Hook} alt="装饰" />
        </div>
        <h2 className='text-xl font-bold text-center pb-6 border-b border-gray-100'>
          <div className='flex justify-center items-center'>
            <img src={Zuo} className='w-3 h-7 mr-1.5' alt="左括号" /> 
            明细解析 
            <img src={You} className='w-3 h-7 ml-1.5' alt="右括号" />
          </div>
        </h2>
        {detailAnalysis.map((item, index) => (
          <div className='mt-5' key={index}>
            <h3 className="text-sm/5 font-semibold tracking-tight text-[#222222] leading-6">
              {item.dimension_name || '未知维度'}
              <span className={`borderBottomLine relative z-10 font-black text-lg`} 
                    style={{ fontFamily: 'SpeedeeApp-BoldItalic' }}>
                <span className='relative z-50'>{item.score || 0}</span>
              </span> 分
            </h3>
            <p className='text-[#222222] mt-[5px]'>{item.comment || '暂无评语'}</p>
          </div>
        ))}
      </div>
      <div className='btnBG mb-5'></div>
    </div>
  );
}